/**
 * This file is loaded via the <script> tag in the index.html file and will
 * be executed in the renderer process for that window. No Node.js APIs are
 * available in this process because `nodeIntegration` is turned off and
 * `contextIsolation` is turned on. Use the contextBridge API in `preload.js`
 * to expose Node.js functionality from the main process.
 */

const { ipcRenderer } = require('electron')

const information = document.getElementById('info')
information.innerText = `本应用正在使用 Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), 和 Electron (v${versions.electron()})`

const func = async () => {
  const response = await window.versions.ping2()
  console.log(response) // 打印 'pong'
}

func()

console.log('window.myAPI', window.myAPI)
window.myAPI.doAThing()
// => undefined

// // 1、获取ID为btn的选择器
// const btn = this.document.querySelector('#btn')

// // 2、创建窗口引用
// const BrowserWindow = require('electron')

// // 3、打开窗口
// window.onload = function () {
//   btn.onclick = () => {
//     newWin = new BrowserWindow({ width: 300, height: 200 })

//     newWin.loadFile('test1.html')

//     newWin.on('close', () => {
//       newWin = null
//     })
//   }
// }

const setButton = document.getElementById('btn')
const titleInput = document.getElementById('title')
setButton.addEventListener('click', () => {
  const title = titleInput.value
  console.log(title)
  window.electronAPI.setTitle(title)
})

const btn = document.getElementById('btn2')
const filePathElement = document.getElementById('filePath')

btn.addEventListener('click', async () => {
  const filePath = await window.electronAPI.openFile()
  filePathElement.innerText = filePath
})

const counter = document.getElementById('counter')

window.electronAPI.handleCounter((event, value) => {
  console.log(event, value)
  const oldValue = Number(counter.innerText)
  const newValue = oldValue + value
  counter.innerText = newValue
  event.sender.send('counter-value', newValue)
})

const channel = new MessageChannel()
const port1 = channel.port1
const port2 = channel.port2

port2.postMessage({ answer: 42 })

ipcRenderer.postMessage('port', null, [port1])
